package com.logos.cartoon.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.logos.cartoon.enums.AiModelEnum;
import com.logos.cartoon.resp.ChatResponse;
import com.logos.cartoon.service.ErenService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class ErenServiceImpl implements ErenService {


    public static String createJson(String content) {
        Gson gson = new Gson();
        JsonObject message = new JsonObject();
        message.addProperty("role", "user");
        message.addProperty("content", content);

        JsonArray messages = new JsonArray();
        messages.add(message);

        JsonObject options = new JsonObject();
        options.addProperty("temperature", 0.7);
        options.addProperty("max_tokens", 100);

        JsonObject json = new JsonObject();
        json.addProperty("model", AiModelEnum.AI_LUN.getDesc());
        json.add("messages", messages);
        json.addProperty("stream", false);
        json.add("options", options);

        return gson.toJson(json);
    }
    private static String extractContentAfterThink(String content) {
        // 使用 DOTALL 模式以匹配多行字符串中的任意字符，包括换行符
        Pattern pattern = Pattern.compile("</think>(.*)", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            String extractedContent = matcher.group(1).trim();
            System.out.println("Extracted Content : " + extractedContent);
            return extractedContent;
        } else {
            System.out.println("No match found for </think> tag.");
            return "";
        }
    }
    @Override
    public String chat(String content) {
        // 配置 OkHttp 客户端并设置超时时间
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间为 60 秒
                .writeTimeout(60, TimeUnit.SECONDS) // 设置写入超时时间为 60 秒
                .connectTimeout(15, TimeUnit.SECONDS) // 设置连接超时时间为 15 秒
                .build();

        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(createJson(content), JSON);

        Request request = new Request.Builder()
                .url("http://localhost:11434/api/chat")
                .post(body)
                .build();
        String ret ="服务器繁忙，请稍后再试";
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                log.info("Response Code : " + response.code());
                ret = response.body().string();
                // 解析响应字符串
                Gson gson = new Gson();
                ChatResponse chatResponse = gson.fromJson(ret, ChatResponse.class);
                // 获取 message 中的 content
                String messageContent = chatResponse.getMessage().getContent();
                // 使用正则表达式提取 </think> 标签后面的内容
                ret = extractContentAfterThink(messageContent);
            } else {
                System.out.println("Request failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
}
